import { HttpException, HttpStatus, Injectable } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { Repository } from "typeorm";
import { CreateCourseDto } from "./dto/create-course.dto";
import { Course } from "./entities/course.entity";
import { Class } from "../class/entities/class.entity";
import { UpdateCourseDto } from "./dto/update-course.dto";

@Injectable()
export class CourseService {
  constructor(
    @InjectRepository(Class) private readonly classServer: Repository<Class>,
    @InjectRepository(Course) private readonly courseServer: Repository<Course>
  ) {}

  async create(createCourseDto: CreateCourseDto) {
    const currentClass = await this.classServer.findOne({ where: { id: createCourseDto.classId } });
    if (!currentClass) throw new HttpException("班级不存在", HttpStatus.BAD_REQUEST);
    const result = await this.courseServer.save(createCourseDto);
    currentClass.course = result;
    await this.classServer.save(currentClass);
    return null;
  }

  async update(updateCourseDto: UpdateCourseDto) {
    const currentClass = await this.classServer.findOne({ where: { id: updateCourseDto.classId } });
    if (!currentClass) throw new HttpException("班级不存在", HttpStatus.BAD_REQUEST);
    const result = await this.courseServer.save(updateCourseDto);
    currentClass.course = result;
    await this.classServer.save(currentClass);
    return null;
  }
}
